package nl.rainbowsheep.reisorg.empl.site.controller;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import nl.rainbowsheep.reisorg.empl.site.model.Customer;
import nl.rainbowsheep.reisorg.empl.site.service.CustomerService;
import nl.rainbowsheep.reisorg.empl.site.viewmodel.CustomerViewmodel;
import nl.rainbowsheep.reisorg.empl.site.viewmodel.TripBookingViewmodel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

/**
 * Customer controller to delegate requests
 */
@Controller
@RequestMapping("/customer")
public class CustomerController {

    /**
     * use slf4j logger during debugging
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(CustomerController.class);

    @Autowired
    CustomerService customerService;

//    @RequestMapping(value = {"/index", "", "/"})
//    public String CustomerIndex() {
//        return "customer/index";
//    }
    @RequestMapping(value = {"/index", "", "/"})
    public ModelAndView CustomerIndex() {
        ModelAndView modelandview = new ModelAndView();
        modelandview.addObject("customer", new Customer());
        return modelandview;
    }

    /**
     * Method is necessary to convert string to date.
     *
     * @param request the HttpServletRequest
     * @param binder the ServletRequestDataBinder
     */
    @InitBinder
    protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        dateFormat.setLenient(true);
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
    }

    /**
     * Method to get the view to register and bind a Customer model object to it
     *
     * @return ModelAndView Customer object
     */
    @RequestMapping(value = "/create", method = RequestMethod.GET)
    public ModelAndView getRegisterForm() {
        ModelAndView modelandview = new ModelAndView();
        modelandview.addObject("customer", new CustomerViewmodel());
        return modelandview;
    }

    /**
     * Method to post a customer by CustomerService to rest service.
     *
     * @param customerViewmodel
     * @param bindingResult checks for validation
     * @param model
     * @return viewname for customer index
     */
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    public ModelAndView createCustomer(@ModelAttribute("customerViewmodel") @Valid CustomerViewmodel customerViewmodel, BindingResult bindingResult, ModelAndView model) {
        if (bindingResult.hasErrors()) {
            return model;
        }
        customerViewmodel.getBurritoUser().setId(-1);
        try {
            CustomerViewmodel customerViewmodelSaved = customerService.insertCustomerViewmodel(customerViewmodel);
        } //hacked error voor wanneer username al bezet is.
        catch (Exception ex) {
            bindingResult.rejectValue("burritoUser.username", "error.burritoUser.username_lbl", "An account already exists with this username");
            return model;
        }
        return new ModelAndView("login");
    }

    @RequestMapping(value = "/find", method = RequestMethod.POST)
    @ResponseBody
    public List<Customer> findCustomers(@RequestBody String customerString) {
        Customer customer = new Customer();
        customer.setLastname(customerString);
        List<Customer> customers = customerService.getSearchResult(customer);
        return customers;
    }

    @RequestMapping(value = "/details/{id}", method = RequestMethod.GET)
    public ModelAndView GetCustomer(@PathVariable long id) {
        ModelAndView modelandview = new ModelAndView("customer/details");
        Customer customer = null;
        if (id > 0) {
            customer = customerService.getCustomer(id);
        }
        modelandview.addObject("customer", customer);
        return modelandview;
    }

    @RequestMapping(value = "/findbookings/{id}", method = RequestMethod.GET)
    @ResponseBody
    public ModelAndView findCustomerBookings(@PathVariable long id) {
        List<TripBookingViewmodel> tripbookingViewmodels = null;
        ModelAndView modelandview = new ModelAndView("customer/booking");
        if (id > 0) {
            tripbookingViewmodels = customerService.getTripBookingViewmodelsByByCustomerId(id);
        } else {
            return modelandview;
        }
        modelandview.addObject("bookings", tripbookingViewmodels);
        return modelandview;
    }

}
